/**
 * (created at 2011-1-20)
 */
package qiushuo.mysqlparser.ast.expression.type;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * <code>higherExpr 'COLLATE' collateName</code>
 * 
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class CollateExpression implements Expression {
    private final String collateName;
    private final Expression string;

    public CollateExpression(Expression string, String collateName) {
        this.string = string;
        this.collateName = collateName;
    }

    public String getCollateName() {
        return collateName;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            if (string.getPrecedence() < getPrecedence()) {
                sb.append('(').append(string.generateSql(type)).append(')');
            } else {
                sb.append(string.generateSql(type));
            }
            sb.append(" COLLATE ").append(collateName);
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

    @Override
    public int getPrecedence() {
        return PRECEDENCE_COLLATE;
    }

}
